#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include "mosquitto.h"
#include "struct.h"
#include "callbacks.h"




int connect_to_broker(struct mosquitto 	*mosq,mosquitto_t *mqtt)
{
	int				err=-1;
	int				stop=0;

#if 0
	printf("\n------------Connect information---------\n");
	printf("clientId:%s\n",mqtt->clientId);
	printf("username:%s\n",mqtt->username);
	printf("hostname:%s\n",mqtt->hostname);
	printf("passwd:%s\n",mqtt->passwd);
	printf("port:%d\n",mqtt->port);
	printf("topic:%s\n",mqtt->topic);
#endif

	err=mosquitto_lib_init();
	if(err!=MOSQ_ERR_SUCCESS)
	{
		printf("'mosquitto_lib_init' failure:%s\n",mosquitto_strerror(err));
		return -1;

	}

	mosq=mosquitto_new(mqtt->clientId,false,(void *)mqtt);
	if(mosq==NULL)
	{
		printf("mosquitto_new fialure\n");
		return -1;
	}

	mosquitto_connect_callback_set(mosq, connect_pub_callback);
	mosquitto_subscribe_callback_set(mosq, connect_sub_callback);
//	mosquitto_message_callback_set(mosq, connect_message_callback);
	mosquitto_disconnect_callback_set(mosq, connect_disconnect_callback);


	if((mosquitto_username_pw_set(mosq,mqtt->username,mqtt->passwd))!=0)
	{
		printf("Error:Failure setting username or password!\n");
		return -1;
	}

	err=mosquitto_connect(mosq,mqtt->hostname,mqtt->port,60);

	if(MOSQ_ERR_SUCCESS!=err)
	{
		printf("mosquitto_connect error:%s\n",mosquitto_strerror(err));
	}



	while(!stop)
	{
		if(mosquitto_connect(mosq,mqtt->hostname,mqtt->port,60))
		{
			printf("Error:Failed connecting cloud.\n\r");
			sleep(1);
			return -1;
		}

		mosquitto_loop_forever(mosq, -1, 1);

		sleep(6);



	}


CleanUp:
	mosquitto_lib_cleanup();
	mosquitto_destroy(mosq);



}


